<template>
  <div class="forget-box">
    <p class="title">密码找回</p>
    <el-form ref="forgetForm" :model="forgetForm" :rules="rules">
      <!-- 第一步:验证手机号 -->
      <template v-if="step === 'verify'">
        <!-- 手机号 -->
        <el-form-item prop="mobile">
          <el-input v-model="forgetForm.mobile" placeholder="请输入注册手机号">
            <template #prepend>
              <el-select v-model="areaCode" placeholder="请选择">
                <el-option label="+86" value="1" />
              </el-select>
            </template>
          </el-input>
        </el-form-item>

        <!-- 图形验证码 -->
        <el-form-item prop="imageCode">
          <el-row :gutter="20">
            <el-col :span="16">
              <el-input
                v-model="forgetForm.imageCode"
                placeholder="请输入图形验证码"
              />
            </el-col>
            <el-col :span="8">
              <div class="code-img" @click="refreshCode">
                <img :src="codeSrc" alt="验证码" />
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <!-- 短信验证码 -->
        <el-form-item prop="smsCode">
          <el-input v-model="forgetForm.smsCode" placeholder="请输入短信验证码">
            <template #append>
              <el-button @click="sendCode" :disabled="sending">
                {{ sendBtnText }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="submit-btn" @click="nextStep">
            下一步
          </el-button>
        </el-form-item>
      </template>

      <!-- 第二步:重置密码 -->
      <template v-else>
        <!-- 新密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="forgetForm.password"
            type="password"
            placeholder="请设置新密码"
            show-password
          />
        </el-form-item>

        <!-- 确认新密码 -->
        <el-form-item prop="passwordConfirm">
          <el-input
            v-model="forgetForm.passwordConfirm"
            type="password"
            placeholder="请确认新密码"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="submit-btn" @click="handleReset">
            确定
          </el-button>
        </el-form-item>
      </template>
    </el-form>

    <!-- 返回登录 -->
    <div class="login-entry">
      <p>
        <span @click="$emit('switchType', 'login')">返回登录</span>
      </p>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, reactive } from 'vue'
import { randomLenNum } from '@/utils'
// import { sendSmsCode, resetPassword } from '@/api/auth'
import { ElMessage } from 'element-plus'

export default defineComponent({
  name: 'ForgetPassword',
  
  emits: ['switchType'],

  setup(props, { emit }) {
    const forgetForm = reactive({
      mobile: '',
      imageCode: '',
      smsCode: '',
      password: '',
      passwordConfirm: ''
    })

    const rules = {
      mobile: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      imageCode: [
        { required: true, message: '请输入图形验证码', trigger: 'blur' }
      ],
      smsCode: [
        { required: true, message: '请输入短信验证码', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 8, message: '密码不能少于8位', trigger: 'blur' },
        { 
          pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,}$/,
          message: '密码必须包含大小写字母、数字和特殊字符',
          trigger: 'blur'
        }
      ],
      passwordConfirm: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== forgetForm.password) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    const step = ref('verify')
    const areaCode = ref('1')
    const codeSrc = ref('')
    const sending = ref(false)
    const sendBtnText = ref('发送验证码')
    let timer = null

    // 刷新验证码
    const refreshCode = () => {
      forgetForm.imageCode = ''
      const randomStr = randomLenNum(4, true)
      codeSrc.value = `/api/code?randomStr=${randomStr}`
    }

    // 发送短信验证码
    const sendCode = async () => {
      if (!forgetForm.mobile) {
        ElMessage.warning('请先输入手机号')
        return
      }
      if (!forgetForm.imageCode) {
        ElMessage.warning('请先输入图形验证码')
        return
      }

      try {
        sending.value = true
        await sendSmsCode({
          mobile: forgetForm.mobile,
          imageCode: forgetForm.imageCode,
          type: 'reset'
        })
        
        let count = 60
        sendBtnText.value = `${count}s`
        
        timer = setInterval(() => {
          count--
          if (count <= 0) {
            clearInterval(timer)
            sending.value = false
            sendBtnText.value = '发送验证码'
          } else {
            sendBtnText.value = `${count}s`
          }
        }, 1000)
      } catch (error) {
        sending.value = false
        refreshCode()
      }
    }

    // 下一步
    const nextStep = () => {
      if (!forgetForm.mobile || !forgetForm.imageCode || !forgetForm.smsCode) {
        ElMessage.warning('请填写完整信息')
        return
      }
      step.value = 'reset'
    }

    // 重置密码
    const handleReset = async () => {
      try {
        await resetPassword({
          mobile: forgetForm.mobile,
          smsCode: forgetForm.smsCode,
          newPassword: forgetForm.password
        })
        
        ElMessage.success('密码重置成功')
        emit('switchType', 'login')
      } catch (error) {
        console.error(error)
      }
    }

    // 初始化验证码
    refreshCode()

    return {
      forgetForm,
      rules,
      step,
      areaCode,
      codeSrc,
      sending,
      sendBtnText,
      refreshCode,
      sendCode,
      nextStep,
      handleReset
    }
  }
})
</script>

<style lang="scss" scoped>
.forget-box {
  position: relative;
  padding: 20px;
  border-radius: 8px;
  background: #fff;

  .title {
    font-size: 20px;
    color: #303133;
    text-align: center;
    margin-bottom: 30px;
  }

  .code-img {
    height: 40px;
    cursor: pointer;
    
    img {
      width: 100%;
      height: 100%;
    }
  }

  .submit-btn {
    width: 100%;
    height: 40px;
    background: #53b7d7;
    border-color: #53b7d7;
    font-size: 16px;
  }

  .login-entry {
    text-align: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #eee;

    p {
      color: #606266;
      font-size: 14px;

      span {
        color: #53b7d7;
        cursor: pointer;
      }
    }
  }
}
</style> 